package com.example.fastshare.alljoyn;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.alljoyn.bus.BusObject;

import com.example.fastshare.ProfileInfo;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.provider.ContactsContract.CommonDataKinds.Im;
import android.provider.MediaStore.Images;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;

enum DATASENDINGSTATUS {
	NONE, SENDING, DONE, ERROR
}

public class Utilities {

	public synchronized static Bitmap getImageLocal(String filePath) {
		return getImageLocal(filePath, BitmapUtil.REQUEST_WIDTH,
				BitmapUtil.REQUEST_HEIGHT);
	}
	

	public synchronized static Bitmap getImageLocal(String filePath,
			int reqWidth, int reqHeight) {
		if (reqWidth == -1 || reqHeight == -1) { // no subsample and no
			return BitmapFactory.decodeFile(filePath);
		} else {
			// First decode with inJustDecodeBounds=true to check dimensions
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(filePath, options);

			// Calculate inSampleSize
			options.inSampleSize = BitmapUtil.calculateInSampleSize(options,
					reqWidth, reqHeight);

			// Decode bitmap with inSampleSize set
			options.inJustDecodeBounds = false;

			return BitmapFactory.decodeFile(filePath, options);
		}
	}

	public synchronized static Bitmap getImageLocal(String filePath, int percent) {
		if (percent > 90) { // no subsample and no
			return BitmapFactory.decodeFile(filePath);

		} else {
			// First decode with inJustDecodeBounds=true to check dimensions
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeFile(filePath, options);
			// Calculate inSampleSize
			options.inSampleSize = BitmapUtil.calculateInSampleSize(options,
					percent);
			// Decode bitmap with inSampleSize set
			options.inJustDecodeBounds = false;
			return BitmapFactory.decodeFile(filePath, options);
		}
	}

	public synchronized static String EncodeFromString(String data) {
		return Base64.encodeToString(data.getBytes(), Base64.DEFAULT);
	}

	public synchronized static String EncodeFromImage(Bitmap image) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 50, stream);
		byte[] byteArray = stream.toByteArray();
		return Base64.encodeToString(byteArray, Base64.DEFAULT);
	}

	public synchronized static String DecodeToString(String data)
			throws UnsupportedEncodingException {
		return new String(Base64.decode(data, Base64.DEFAULT), "UTF-8");
	}

	public synchronized static Bitmap DecodeToImage(String data) {
		byte[] image = Base64.decode(data, Base64.DEFAULT);
		return BitmapFactory.decodeByteArray(image, 0, image.length);
	}

	public synchronized static Bitmap createBitmapFromList(List<Image> listImage) {
		int width = 0;
		int height = 0;
		for (Image img : listImage) {
			width = img.getWidth();
			height += img.getHeight();
		}
		Bitmap result = Bitmap.createBitmap(width, height, Config.ARGB_8888);
		Canvas combine = new Canvas(result);
		int posX = 0;
		int posY = 0;
		for (Image img : listImage) {
			combine.drawBitmap(img.makeImage(), posX, posY, null);
			posY += img.getHeight();
		}
		return result;
	}

	public synchronized static List<Image> SplitBitmap(String imageName,
			Bitmap image) {
		int imageWid = image.getWidth();
		int imageHei = image.getHeight();
		int width = 100;
		int height = 100;
		List<Image> result = new ArrayList<Image>();
		int posX = 0;
		int posY = 0;
		int row = 0;
		int col = 0;
		if (imageHei % height != 0) {
			row = imageHei / height + 1;
		} else {
			row = imageHei / height;
		}
		if (imageWid % width != 0) {
			col = imageWid / width + 1;
		} else {
			col = imageWid / width;
		}

		Log.e("Image", "Total row " + (row));
		Log.e("Image", "Total column " + (col));

		for (int y = 0; y < row; y++) {
			Image img = new Image(y, imageName);
			for (int x = 0; x < col; x++) {

				if (imageHei - posY < height && imageWid - posX < width
						&& (imageWid - posX != 0 && imageHei - posY != 0)) {
					Log.e("Image", "image: " + posX + "-" + posY + "-"
							+ (imageWid - posX) + "-" + (imageHei - posY));
					Bitmap _pieceadd = Bitmap.createBitmap(image, posX, posY,
							imageWid - posX, imageHei - posY);
					img.AddImage(_pieceadd);
				} else {
					if (imageHei - posY < height && imageHei - posY > 0
							&& imageWid - posX != 0) {
						Log.e("Image", "image: " + posX + "-" + posY + "-"
								+ (width - 1) + "-" + (imageHei - posY));
						Bitmap _pieceadd = Bitmap.createBitmap(image, posX,
								posY, width - 1, imageHei - posY);
						img.AddImage(_pieceadd);
					} else {
						if (imageWid - posX < width && imageWid - posX > 0
								&& imageHei - posY != 0) {
							Log.e("Image", "image: " + posX + "-" + posY + "-"
									+ (imageWid - posX) + "-" + (height - 1));
							Bitmap _pieceadd = Bitmap.createBitmap(image, posX,
									posY, imageWid - posX, height - 1);
							img.AddImage(_pieceadd);
						} else {
							if (imageWid - posX != 0 && imageHei - posY != 0) {
								Log.e("Image", "image: " + posX + "-" + posY
										+ "-" + (width - 1) + "-"
										+ (height - 1));
								Bitmap _piece = Bitmap.createBitmap(image,
										posX, posY, width - 1, height - 1);
								img.AddImage(_piece);
							}
						}
					}
				}
				posX += width;
			}
			result.add(img);
			posY += height;
			posX = 0;
		}
		image.recycle();
		return result;
	}

	public static void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			// pre-condition
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight
				+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
	}

	public static ProfileInfo loadProfile(Activity _activity) {

		try {
			File myFile = new File("/sdcard/Fastshare/profile.txt");
			FileInputStream fIn = new FileInputStream(myFile);
			BufferedReader myReader = new BufferedReader(new InputStreamReader(
					fIn));
			String line;
			String userName = null;
			String avatar = null;
			String macAddress = null;
			while ((line = myReader.readLine()) != null) {
				String[] info = line.split("//");
				userName = info[0].replace("username:", "");
				macAddress = info[1].replace("macaddress:", "");
				avatar = info[2].replace("avatar:", "");
			}
			myReader.close();
			ProfileInfo _info = new ProfileInfo(userName, macAddress, avatar);
			return _info;
		} catch (Exception e) {
			return null;
		}
	}

	public static void saveProfile(Activity _activity, String userName,
			String avatar) {
		final File dir = new File(Environment.getExternalStorageDirectory()
				+ "/Fastshare/");
		if (dir.exists() == false) {
			dir.mkdirs(); // create folders where write files
		}
		try {
			// deviceName.setText(macAddress);
			File myFile = new File("/sdcard/Fastshare/profile.txt");
			myFile.createNewFile();
			FileOutputStream fOut = new FileOutputStream(myFile);
			OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
			WifiManager wifiManager = (WifiManager) _activity
					.getSystemService(Context.WIFI_SERVICE);
			WifiInfo wInfo = wifiManager.getConnectionInfo();
			String macAddress = wInfo.getMacAddress();
			myOutWriter.append("username:" + userName + "//macaddress:"
					+ macAddress + "//avatar:" + avatar);
			myOutWriter.close();
			fOut.close();

		} catch (Exception e) {
			Toast.makeText(_activity.getBaseContext(), e.getMessage(),
					Toast.LENGTH_SHORT).show();
		}
	}

	static class BitmapUtil {
		public static final int REQUEST_WIDTH = 100;
		public static final int REQUEST_HEIGHT = 100;

		public synchronized static int calculateInSampleSize(
				BitmapFactory.Options options) {
			return calculateInSampleSize(options, REQUEST_WIDTH, REQUEST_HEIGHT);
		}

		public synchronized static int calculateInSampleSize(
				BitmapFactory.Options options, int reqWidth, int reqHeight) {

			// Raw height and width of image
			final int height = options.outHeight;
			final int width = options.outWidth;
			int inSampleSize = 1;

			if (height > reqHeight || width > reqWidth) {
				// Calculate ratios of height and width to requested height and
				// width
				final int heightRatio = Math.round((float) height
						/ (float) reqHeight);
				final int widthRatio = Math.round((float) width
						/ (float) reqWidth);

				// Choose the smallest ratio as inSampleSize value, this will
				// guarantee
				// a final image with both dimensions larger than or equal to
				// the
				// requested height and width.
				inSampleSize = heightRatio < widthRatio ? heightRatio
						: widthRatio;
			}
			return inSampleSize;
		}

		public synchronized static int calculateInSampleSize(
				BitmapFactory.Options options, int percent) {

			// Raw height and width of image
			final int height = options.outHeight;
			final int width = options.outWidth;
			int inSampleSize = 1;

			if (percent < 100 && (height > 800 || width > 1000)) {
				// Calculate ratios of height and width to requested height and
				// width
				float reqHeight = height * percent / 100;
				float reqWidth = width * percent / 100;
				final int heightRatio = Math.round((float) height
						/ (float) reqHeight);
				final int widthRatio = Math.round((float) width
						/ (float) reqWidth);

				// Choose the smallest ratio as inSampleSize value, this will
				// guarantee
				// a final image with both dimensions larger than or equal to
				// the
				// requested height and width.
				inSampleSize = heightRatio < widthRatio ? heightRatio
						: widthRatio;
			}

			return inSampleSize;
		}
	}
}
